#!usr/bin/env python3
# -*- encoding: utf-8 -*-
import json
import time
import os
import requests
import jenkinsapi
import sys
import urllib3


# from yaml_manager import read_sign_yaml


class JenkinsApiStudy:
    """
    Jenkins API 学习类，用于连接Jenkins服务器并获取Job信息
    """

    def __init__(self):
        """
        实现对jenkins的连接
        """
        jenkins_url = "http://172.22.1.77:8080"
        username = "xxxxx"
        password = "xxxx"
        self.my_jenkins = jenkinsapi.jenkins.Jenkins(jenkins_url, username, password, use_crumb=True, timeout=60)

    def get_job_info(self, job_name):
        """
        jenkinsapi 获取Job信息
        :param job_name: Job名称
        :return: Job对象，Job URL，最后一次构建编号，报告URL
        """
        # 获取job对象
        my_job = self.my_jenkins.get_job(job_name)
        print(my_job)
        print(my_job.url)
        job_url = my_job.url
        print(my_job.get_last_completed_buildnumber())
        job_last_number = my_job.get_last_completed_buildnumber()
        report_url = job_url + str(job_last_number + 1) + '/allure'
        return my_job, job_url, job_last_number, report_url


class Send_DingTalk(JenkinsApiStudy):
    """
    发送钉钉消息类，继承JenkinsApiStudy类以获取Jenkins Job信息
    """

    def __init__(self, job_name):
        """
        初始化Send_DingTalk类
        :param job_name: Job名称
        """
        super().__init__()
        self.my_job, self.job_url, self.job_last_number, self.report_url = self.get_job_info(job_name)

    def push_message(self):
        """
        推送消息到钉钉
        """
        content = {}
        print(os.getcwd())
        file_path = os.path.dirname(os.getcwd()) + fr'/{re_data}/allure-report/export/prometheusData.txt'

        f = open(file_path)
        for line in f.readlines():
            launch_name = line.strip('\n').split(' ')[0]
            num = line.strip('\n').split(' ')[1]
            content.update({launch_name: num})
        f.close()
        passed_num = content['launch_status_passed']  # 通过数量
        failed_num = content['launch_status_failed']  # 失败数量
        broken_num = content['launch_status_broken']  # 阻塞数量
        skipped_num = content['launch_status_skipped']  # 跳过数量
        case_num = content['launch_retries_run']  # 总数量
        total_time_str = content['launch_time_duration']
        # 将 total_time 从字符串转换为整数
        try:
            total_time = int(total_time_str)
        except ValueError:
            print(f"无法将 total_time 转换为整数: {total_time_str}")
            return None
        # 将毫秒转换为秒
        total_time_s = total_time / 1000
        # 将秒转换为分钟
        total_time_min = total_time_s / 60

        """
        钉钉消息发送，通过webhook发送消息
        """
        webhook = 'xxxxxxxxxxxxxxxxxxx'
        # 这里一定要注意！！！content:内容要包含钉钉的关键字，不然会一直报错不通过！！！!
        # 获取当前时间
        from datetime import datetime
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M")

        # 构建第一类消息内容
        message = (
            f"【综合】-UI自动化测试结果\n"
            f"【用例数量】: {case_num}\n"
            f"【成功数量】: {passed_num}\n"
            f"【失败数量】: {failed_num}\n"
            f"【阻塞数量】: {broken_num}\n"
            f"【跳过数量】: {skipped_num}\n"
            f"【总用时】: {total_time_s:.2f} s\n"
            f"【执行时间】: {current_time}\n"
            f"【测试报告】: {self.report_url}\n\n"
        )

        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            }
        }
        print(data)
        try:
            response = requests.post(url=webhook, json=data, headers=headers, timeout=50)
            if response.status_code == 200:
                print("钉钉通知发送成功")
            else:
                print("钉钉通知发送失败")
        except Exception as e:
            print("钉钉通知发送失败")


if __name__ == '__main__':
    # J = Send_DingTalk("pytest_L2_homework")
    # job_result = J.push_message()
    # print(job_result)
    re_data = sys.argv[1]
    J = Send_DingTalk(re_data)
    job_result = J.push_message()
